package com.itheima.ms.aop;

import com.itheima.ms.anno.DS;
import com.itheima.ms.enums.DBRoleEnum;
import com.itheima.ms.tl.DataSourceTypeTL;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 通过业务代码动态切换数据源
 * 识别执行方法上得注解
 */
@Component @Aspect
//设置order=0,执行时机优先于AbstractRoutingDataSource.determineCurrentLookupKey
@Order(0)
public class SwitchDSAspect {

//    @Pointcut(value = "@annotation(com.itheima.ms.anno.DS)")
    @Pointcut(value = "execution(* com.itheima.ms.service..*.*(*))")
    public void pointCut(){}

    @Around("pointCut()")
    public Object runMethod(ProceedingJoinPoint joinPoint) throws Throwable{
        try {
            //判断要执行的方法使用的数据源
            MethodSignature signature = (MethodSignature)joinPoint.getSignature();
            Method method = signature.getMethod();
            DS dsAnno = method.getAnnotation(DS.class);
            if(dsAnno != null){
                DBRoleEnum value = dsAnno.value();
                System.out.println(value);
                DataSourceTypeTL.setDbRole(value);
            }else{
                DataSourceTypeTL.setDbRole(DBRoleEnum.MASTER);
            }
            return joinPoint.proceed(joinPoint.getArgs());
        }  finally {
            DataSourceTypeTL.clearDbRole();
        }
    }


}
